package ws

import (
	"svr/src/conf"
	"svr/src/eor"
	"svr/src/msg"
	"time"

	"github.com/gorilla/websocket"
)

var DL = websocket.Dialer{
	ReadBufferSize:   32768,
	WriteBufferSize:  32768,
	HandshakeTimeout: 30 * time.Second,
}

const epos_ConnectToServer = "ConnectToServer"

func ConnectToServer(addr string) *msg.Error {
	conn, _, err := DL.Dial("ws://"+addr, nil)
	if err != nil {
		return eor.NewErr(msg.ErrCode_Err_Connected, epos_ConnectToServer, "1", err, " addr:", addr)
	}
	/**       //!#dv dev地址map暂时不用
	dev, err := addAddrDeviceInfo(conn, false) //来自上级服务器的连接
	if xutil.CheckErr(err) {
		return err
	}
	/**/                                 //!#dv
	dev := createDeviceInfo(conn, false) //来自上级服务器的连接
	/**/
	dev.SendMessageDirect(&msg.RegisterDeviceR{ //获得连接之后，立刻注册自己设备类型
		DevType:    conf.ServerConfig.ServerType,
		ListenPort: conf.ServerConfig.ListenPort,
	})
	defer func() {
		if dev != nil {
			dev.Close()
		}
	}()
	for {
		if dev.ReadMessage() != nil {
			break
		}
	}
	return nil
}

/**
func init1() {
	// fmt.Println("redis---------------")
	// rds := redis.NewClient(&redis.Options{
	// 	Addr: "127.0.0.1:6379",
	// 	// Password: "qqqq1111",
	// 	DB: 1,
	// })
	// for i := 0; i < 10; i++ {
	// 	str, err := rds.Set(context.Background(), fmt.Sprintf("s%d", (3+i)*(4+i)), (44+i)*(1+i), 0).Result()
	// 	fmt.Println("=============", str, err)
	// }
	db, err := InitMySql()
	if err != nil {
		fmt.Println("Err 2", err)
	} else {
		fmt.Println("11111111")
	}
	us := &User{
		UserId: 1234567,
		Name:   "aaaa1",
	}
	// err = db.Where("user_id = ? AND name = ?", 123456, "aaaa").FirstOrCreate(us).Error
	// if err != nil {
	// 	fmt.Println("Err 2", err)
	// } else {
	// 	fmt.Println("2222222")
	// }

	err = db.Where("user_id = ?", 123456, "aaaa").Save(us).Error
	if err != nil {
		fmt.Println("Err 2", err)
	} else {
		fmt.Println("2222222")
	}
}

func InitRedis() *redis.Client {
	rds := redis.NewClient(&redis.Options{
		Addr: "127.0.0.1:6379",
		// Password: "qqqq1111",
		DB: 1,
	})
	return rds
}

func InitMySql() (*gorm.DB, error) {
	host := "127.0.0.1"
	port := 3306
	user := "root"
	pass := "qqqq1111"
	dbname := "test"
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		user,
		pass,
		host,
		port,
		dbname)
	fmt.Println("dsn: ", dsn)
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		return nil, err
	}
	db.AutoMigrate(
		&User{},
	)
	return db, nil
}

type User struct {
	gorm.Model
	UserId int64 `gorm:"index"`
	Name   string
}
/**/
